﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibrary.Web
{
    /// <summary>
    /// Manages CSS document.
    /// </summary>
    public class CssDocument : WebFile
    {
        /// <summary>
        /// Gets or sets styles of current document.
        /// </summary>
        public CssStyles Styles { get; set; }
        /// <summary>
        /// Gets refactorized document content.
        /// </summary>
        public string Content 
        { 
            get 
            { 
                return (this.Styles as IBuildable).Build(); 
            } 
        }
        /// <summary>
        /// Creates new empty CSS document.
        /// </summary>
        public CssDocument()
            : base()
        {
            this.Styles = new CssStyles();
        }
        /// <summary>
        /// Creates new empty CSS document with specified name.
        /// </summary>
        /// <param name="Name">Specifies name of current document.</param>
        public CssDocument(string Name)
            : base(Name)
        {
            this.Styles = new CssStyles();
        }
        /// <summary>
        /// Loads CSS styles to document from CSS code string.
        /// </summary>
        /// <param name="cssCode">Specfies CSS code string which has to be parsed.</param>
        public void LoadCss(string cssCode)
        {
            MatchCollection mc = Regex.Matches(cssCode, "([^{}]+{[^{}]*})");
            foreach (Match m in mc)
            {
                CssStyle style = new CssStyle();
                (style as IParsable).Parse(m.Groups[1].Value);
                this.Styles.Add(style);
            }
        }
        /// <summary>
        /// Loads CSS code from file and fills content of current document.
        /// </summary>
        /// <param name="cssFilePath">Specifies path of CSS file which has to be loaded.</param>
        public void LoadFile(string cssFilePath)
        {
            this.LoadCss(System.IO.File.ReadAllText(cssFilePath));
        }
        /// <summary>
        /// Saves CSS code to specfied file.
        /// </summary>
        /// <param name="filePath">Specifies path of file which has to be filled with CSS document.</param>
        public void Save(string filePath)
        {
            System.IO.File.WriteAllText(filePath, (this.Styles as IBuildable).Build());
        }
        /// <summary>
        /// Loads content of CSS file throught overrided method.
        /// </summary>
        /// <param name="Path">Specifies path of file which has to be loaded.</param>
        public override void LoadContent(string Path)
        {
            this.LoadFile(Path);
            base.LoadContent(Path);
        }
    }
}
